import datetime
from django.http import HttpResponse
from openpyxl import Workbook
from io import BytesIO
from urllib.parse import quote



def export_excel(title: str, row_one: list, data: list):
    """
    导出Excel文件
    :param title: 表格标题
    :param row_one: 设置表头
    :param data: 设置要回写的值，必须是每行对应的字段值组成的列表
    :return: 返回Excel文件
    """
    wb = Workbook()  # 创建工作簿
    sheet1 = wb.active  # 获取活动工作表
    sheet1.title = title  # 设置工作表标题

    # 设置表头
    for i in range(1, len(row_one) + 1):  # 从第1行第1列开始写入表头
        sheet1.cell(row=1, column=i).value = row_one[i - 1]

    # 填充数据
    for idx, row_data in enumerate(data, start=2):
        for col_idx, value in enumerate(row_data, start=1):
            sheet1.cell(row=idx, column=col_idx).value = value

    # 将Excel文件保存到内存中
    output = BytesIO()
    wb.save(output)
    output.seek(0)  # 重新定位到开始

    # 设置响应类型为Excel文件
    response = HttpResponse(output.getvalue(), content_type='application/vnd.ms-excel')
    ctime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    file_name = f'{title}_{ctime}.xls'
    file_name = quote(file_name)  # 编码文件名
    response['Content-Disposition'] = f'attachment; filename={file_name}'

    return response